﻿using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Mixr
{
    public partial class UserPopup : Form
    {
        int uid;
        string uname;       //Variables used throughout rest of application after user is logged in
        bool state = false; //Represents state of login window (new user, or returning user?)

        public UserPopup()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)  //Submit button routine
        {
            if(state)  //If a new account is being created, check the input formatting.
            {
                if(User_Password.Text != textPasswordConfirm.Text)
                //Check if they are trying to create a new login and if the passwords match. If not, just stop altogether and try again.
                {
                    Invalid_Login_label.Text = "Passwords do not match, try again.";
                    return;
                }
                if(User_Password.Text.Length > 10 || textPasswordConfirm.Text.Length > 10|| User_Name.Text.Length > 10)
                //Username and password must be under 10 characters; this checks both
                {
                    Invalid_Login_label.Text = "Username and password must be 10 characters or fewer.";
                    return;
                }
            }
            
            //Create query strings for insertion and deletion commmands.
            string Insert_Query
                    = "INSERT INTO [User] (Username, Password, Email) VALUES ('" + Convert.ToString(User_Name.Text) + "', '" + Convert.ToString(User_Password.Text) + "', '" + Convert.ToString(textEmail.Text) + "')";
            string Select_Query
                    = "SELECT [User].UserID, [User].Username FROM [User] WHERE Username = '" + Convert.ToString(User_Name.Text) + "' AND Password = '" + Convert.ToString(User_Password.Text) + "'";

            //Create and open an SQL database connection and command based on the query string.
            string connection_query
                = @"Data Source=.\SQLEXPRESS;AttachDbFilename='|DataDirectory|\UserDatabase.mdf';Integrated Security=True;User Instance=True";
            
            //Create connections and commands for querying and insertion
            SqlConnection connection = new SqlConnection(connection_query);
            SqlCommand query_CMD = new SqlCommand(Select_Query, connection);
            SqlCommand insert_CMD = new SqlCommand(Insert_Query, connection);
            connection.Open();

            //See if the user data already exists.
            SqlDataReader query_read = query_CMD.ExecuteReader();
            bool record = query_read.Read();
            query_read.Close();

            if (state && record) //If the attempted username creation already exists
            {
                Invalid_Login_label.Text = "Sorry, username already exists!";
            }

            else if (!state && !record) //If a user attempts to log in with a bad password/username...
            {
                Invalid_Login_label.Text = "Invalid username or password";
            }

            else if ((state && !record) || (!state && record)) //If everything is all clear to create a username or they are trying to log in
            {
                Invalid_Login_label.Text = "";
                if (state && !record) insert_CMD.ExecuteNonQuery();  //Actually insert data if its a new account attempt

                SqlDataReader query_id = query_CMD.ExecuteReader();
                query_id.Read();
                    
                //Rip user data from user database after inserting it. A bit of a self-check and works around unique UID not being available
                //on creation of new user account.
                uid = (int)query_id["UserID"];
                uname = (string)query_id["Username"];
                query_id.Close();

                //Open the next step of use case; either add local media for the first time or bring them to main window.
                if (state && !record) new AddLocalMedia(uid, uname).Show();
                else if (!state && record) new MixrWindow(uid, uname).Show();
                this.Hide();
            }

            else  //Something is wrong if this is reached. Should never happen.
            {
                Invalid_Login_label.Text = "Something weird happened. Try again.";
            }

            connection.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        //Change the state of the login window back and forth between login or create new user with this button.
        {
            if (!state)
            {
                this.Height = this.Height + 50;
                this.Controls.Add(this.passwordLabel2);
                this.Controls.Add(this.emailLabel);
                this.Controls.Add(this.textPasswordConfirm);
                this.Controls.Add(this.textEmail);
                this.button2.Text = "Cancel";
                state = true;
            }
            else
            {
                this.Height = this.Height - 50;
                this.Controls.Remove(this.passwordLabel2);
                this.Controls.Remove(this.emailLabel);
                this.Controls.Remove(this.textPasswordConfirm);
                this.Controls.Remove(this.textEmail);
                this.button2.Text = "New User?";
                state = false;
            }

        }

        private void UserPopup_Load(object sender, EventArgs e)
        {

        }
    }
}
